package com.yxt.admin.controller;

import com.yxt.admin.bean.TokenService;
import com.yxt.admin.config.ResourceServerConfig;
import com.yxt.admin.dto.UserDto;
import com.yxt.admin.entity.SysRole;
import com.yxt.admin.service.ISysRoleService;
import com.yxt.admin.service.ISysUserService;
import com.yxt.admin.service.impl.SysPermissionService;
import com.yxt.admin.utils.SecurityUtils;
import com.yxt.common.annotation.Log;
import com.yxt.common.constant.Constant;
import com.yxt.common.enums.BusinessType;
import com.yxt.common.utils.ServletUtils;
import com.yxt.common.utils.StringUtils;
import com.yxt.common.utils.ajax.PageUtils;
import com.yxt.common.utils.ajax.R;
import com.yxt.common.utils.redis.RedisCache;
import com.yxt.common.utils.sign.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 角色信息
 * 
 */
@RestController
@RequestMapping("/admin/role")
public class SysRoleController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private RedisCache redisCache;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;
    
    @Autowired
    private SysPermissionService permissionService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    @Autowired
    TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params, SysRole role)
    {
        PageUtils page = roleService.queryPage(params,role);
        return R.ok().put("data", page);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable Long roleId)
    {
        return R.ok().put("data",roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysRole role)
    {
        if (Constant.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (Constant.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(tokenService.getLoginUser().getUser().getUserName());

        return roleService.insertRole(role) > 0 ? R.ok() : R.error();

    }

    /**
     * 修改保存角色
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (Constant.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (Constant.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }


        role.setUpdateBy(tokenService.getLoginUser().getUser().getUserName());
        
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
            Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
            String userId = String.valueOf(stringStringMap.get("userId"));
            UserDto loginUser = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);

            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));

                loginUser.setLoginTime(System.currentTimeMillis());
                loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
                redisCache.setCacheObject(Constant.USER_ACCOUNT_KEY+String.valueOf(loginUser.getUser().getUserId()), loginUser, expireTime, TimeUnit.MINUTES);

            }
            return R.ok();
        }
        return R.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        return roleService.authDataScope(role) > 0 ? R.ok() : R.error();
    }

    /**
     * 状态修改
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(tokenService.getLoginUser().getUser().getUserName());

        return roleService.updateRoleStatus(role) > 0 ? R.ok() : R.error();
    }

    /**
     * 删除角色
     */
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds)
    {
        return roleService.deleteRoleByIds(roleIds) > 0 ? R.ok() : R.error();
    }

}
